package com.zzgc.common.fliter;

import com.alibaba.fastjson.JSONObject;
import com.zzgc.common.response.HttpStatus;
import com.zzgc.common.response.Result;
import org.apache.commons.compress.archivers.dump.UnrecognizedFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.AccessException;

/**
 * Root角色过滤器</br>
 * 不具有Root角色的请求将被过滤
 */
@Component
public class RootRoleFilter implements Filter {

    /**
     * 核心鉴权操作执行域
     */
    @Autowired
    private StatelessRealm statelessRealm;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(isAccessAllowed(servletRequest,servletResponse)){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            onAuthorizationFail(servletResponse,"您没有相应的权限！");
        }
    }

    @Override
    public void destroy() {

    }

    /**
     * 过滤器处理异常方法
     * 返回认证失败的响应
     * @param servletResponse
     * @throws IOException
     */
    private void onAuthorizationFail(ServletResponse servletResponse, String errorMsg) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
       // httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        Result result = Result.builder().code(500).msg(errorMsg).build();
        httpResponse.setCharacterEncoding("utf-8");
        httpResponse.setContentType("application/json");
        httpResponse.getWriter().write(JSONObject.toJSONString(result));
    }

    // 判断是否有该角色的权限
    private boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String tokenStr = request.getHeader("token");
        if(tokenStr == null){// 请求头中没有Token
            return false;
        }
        try{
            return statelessRealm.hasRole(tokenStr, Role.COUNTY.value());
        }catch (Exception e){
            return false;
        }
        //return true;
    }

}
